<template>
  <div class="pdf-wrap scrollbar-style">
    <vue-pdf-embed
        :source="state.source"
        v-if="state.pdfShow"
        :style="scaleFun"
        class="vue-pdf-embed"
        ref="vuePdfRef"
        :page="state.pageNum"
        @loaded="onPdfLoaded"
    />
  </div>
  <div class="page-tool">
    <div class="page-tool-item" @click="lastPage">上一页</div>
    <div class="page-tool-item">{{ state.pageNum }}/{{ state.numPages }}</div>
    <div class="page-tool-item" @click="nextPage">下一页</div>
    <div class="page-tool-item" @click="pageZoomOut">放大</div>
    <div class="page-tool-item" @click="pageZoomIn">缩小</div>
    <div class="page-tool-item" @click="PDFPrint">打印</div>
  </div>
</template>
<script setup>
import { reactive, computed, ref } from "vue";
const vuePdfRef = ref(null);

const props = defineProps({
  pdfUrl: {
    type: String,
    required: true
  }
});

const scaleFun = computed(() => `transform:scale(${state.scale})`);
const state = reactive({
  source: props.pdfUrl, // 预览pdf文件地址
  pageNum: 1, // 当前页面
  scale: 1, // 缩放比例
  numPages: 1, // 总页数
  pdfShow: true // pdf是否显示
});

const onPdfLoaded = pdf => {
  state.numPages = pdf.numPages;
};

// 上一页
function lastPage() {
  if (state.pageNum > 1) {
    state.pageNum -= 1;
  }
}

// 下一页
function nextPage() {
  if (state.pageNum < state.numPages) {
    state.pageNum += 1;
  }
}

// 放大
function pageZoomOut() {
  if (state.scale < 2) {
    state.scale += 0.1;
  }
}

// 缩小
function pageZoomIn() {
  if (state.scale > 1) {
    state.scale -= 0.1;
  }
}

// 打印/下载
function PDFPrint() {
  vuePdfRef.value?.print(300, "合同", true); // 打印：参数1为分辨率 参数2为文件名称 参数3为是否打印所有页面
}
</script>
<style lang="scss" scoped>
.vue-pdf-embed {
  text-align: center;
  width: 60%;
  margin: 0 auto;
  height: 80vh;
}

.pdf-wrap {
  overflow-y: auto;
  //background: #f6f8fa;
  background: rgb(66, 66, 66);
  border-radius: 4px 4px 4px 4px;
}

.page-tool {
  position: absolute;
  bottom: 35px;
  padding-left: 15px;
  padding-right: 15px;
  display: flex;
  align-items: center;
  //background: rgba(3, 67, 109, 0.075);
  background: rgb(66, 66, 66);
  color: white;
  //color: rgba(2, 1, 41, 0.507);
  border-radius: 19px;
  z-index: 100;
  cursor: pointer;
  margin-left: 52%;
  transform: translateX(-50%);
}

.page-tool-item {
  padding: 8px 15px;
  padding-left: 10px;
  cursor: pointer;
}
</style>
